package com.whut.report;

import com.alibaba.fastjson.JSONArray;
import com.whut.common.ReportCommonFunc;
import com.whut.model.ContractTaskProject;
import com.whut.model.MachineInfo;
import com.whut.parMapper.ParProblemCollectDetailMapper;
import com.whut.parMapper.ParProblemDescriptionMapper;
import com.whut.parMapper.ParSystemMapper;
import com.whut.parMapper.utils.MapperUtils;
import com.whut.service.impl.ReportServiceImpl;
import com.whut.utils.MDoc;
import com.whut.v_dataMap.equipReportDataMap.*;
import com.whut.v_model.ProblemCollectDetail;
import com.whut.v_vo.equipReportBaseVO.*;
import org.apache.commons.beanutils.BeanMap;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class EquipReport {
    private ParSystemMapper parSystemMapper;
    private ParProblemDescriptionMapper parProblemDescriptionMapper;
    private ParProblemCollectDetailMapper parProblemCollectDetailMapper;
    private ReportServiceImpl reportServiceImpl;

    private MapperUtils mapperUtils;

    private int checkId;
    private int projectId;
    private boolean isNew;
    public static final int WIDTH = 718;
    public static final int HEIGHT = 468;
    public EquipReport(ParSystemMapper parSystemMapper,
                                      ParProblemDescriptionMapper parProblemDescriptionMapper,
                                      ParProblemCollectDetailMapper parProblemCollectDetailMapper,
                                      ReportServiceImpl reportServiceImpl,
                                      MapperUtils mapperUtils) {
        this.parSystemMapper = parSystemMapper;
        this.parProblemDescriptionMapper = parProblemDescriptionMapper;
        this.parProblemCollectDetailMapper = parProblemCollectDetailMapper;
        this.reportServiceImpl = reportServiceImpl;
        this.mapperUtils=mapperUtils;
    }



    public String equipReport(int checkId, int projectId) {
        //报告最终dataMap，存储所有报告所需数据
        ReportFinalMap dataMap = new ReportFinalMap();

        //生成时间
        DateTimeFormatter dateTimeFormatterYear = DateTimeFormatter.ofPattern("yyyy");
        String year = dateTimeFormatterYear.format(LocalDate.now());
        dataMap.setYear(year);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String reportDate = dateTimeFormatter.format(LocalDate.now());
        dataMap.setReportDate(reportDate);

        //第一部分 --- 一、工程概况
        ContractTaskProject contractTaskProject = mapperUtils.getContractTaskProjectMapper().selectAllByProjectId(projectId);

        dataMap.setArea(contractTaskProject.getArea());
        dataMap.setProjectName(contractTaskProject.getProjectName());
        dataMap.setJsUnit(contractTaskProject.getJsUnit());
        dataMap.setJlUnit(contractTaskProject.getJlUnit());
        dataMap.setSgUnit(contractTaskProject.getSgUnit());
        dataMap.setProgress(contractTaskProject.getProgress());

        List<MachineInfo> equipInfo = mapperUtils.getMachineinfoMapper().getMachineInfoByProjectId(projectId);
        List<EquipInfoListMap> equipInfoList = new ArrayList<>();
        for (MachineInfo mi : equipInfo) {
            EquipInfoListMap equipInfoMap = new EquipInfoListMap();
            equipInfoMap.setEquipModel(mi.getEquipModel());
            Integer machineTypeNum = mi.getMachineType();
            String machineType = "无";
            if (reportServiceImpl.configIsNull(machineTypeNum)) {
                machineType = parSystemMapper.getName4ByName4Id(machineTypeNum);
            }
            equipInfoMap.setMachineType(machineType);
            equipInfoMap.setEquipNum(mi.getEquipNum());
            equipInfoMap.setDetectionUnit(mi.getDetectionUnit());
            equipInfoMap.setInstallRemoveUnit(mi.getInstallRemoveUnit());
            equipInfoList.add(equipInfoMap);
        }
        dataMap.setEquipInfoList(equipInfoList);

        //第一部分 --- 二、评估结果
        List<EvaluatieResultListMap> evaluatieResultList = new ArrayList<>();
        for (MachineInfo mi : equipInfo) {
            //检查结果意见判断标志
            boolean flag = true;

            EvaluatieResultListMap evaluatieResultMap = new EvaluatieResultListMap();

            //第四级id
            Integer machineTypeNum = mi.getMachineType();
            String machineType = "无";
            if (reportServiceImpl.configIsNull(machineTypeNum)) {
                machineType = parSystemMapper.getName4ByName4Id(machineTypeNum);
            }
            evaluatieResultMap.setMachineType(machineType);
            evaluatieResultMap.setEquipNum(mi.getEquipNum());

            //获取所有第五级id
            List<Integer> fifthIdList =parSystemMapper.getFifthId(machineTypeNum);
            List<FifthListVO> allFifthList = parProblemDescriptionMapper.getAllProblemDesAndOthers(fifthIdList);
            List<GradeFifthListMap> gradeFifthList = new ArrayList<>();
            for (FifthListVO fifthObj : allFifthList) {
                GradeFifthListMap gradeFifthMap = new GradeFifthListMap();
                String pName5 = parSystemMapper.getName4ByName4Id(fifthObj.getFifthId());
                gradeFifthMap.setpName5(pName5);
                //有问题第六级list
                List<SixthListVO> sixthList = fifthObj.getSixthList();
                List<GradeSixthListMap> gradeSixthList = new ArrayList<>();
                int index = 1;

                for (SixthListVO sixthObj : sixthList) {
                    GradeSixthListMap gradeSixthMap = new GradeSixthListMap();
                    gradeSixthMap.setIndex(index);
                    gradeSixthMap.setpName5(pName5);
                    gradeSixthMap.setpName6(sixthObj.getpName6());

                    Double point6 = 0.0d;
                    //问题描述list
                    List<AllProblemDescriptionListVO> problemDesList = sixthObj.getProblemDescriptionList();
                    List<ProblemDescriptionListMap> problemDescriptionListFromPD = new ArrayList<>();
                    int indexProblemDes = 1;
                    for (AllProblemDescriptionListVO pdObj : problemDesList) {
                        ProblemDescriptionListMap problemDescriptionMap = new ProblemDescriptionListMap();
                        point6 = Double.parseDouble(pdObj.getPoint());
                        String deductPoint = pdObj.getDeductPoint();
                        String deductPointRange = reportServiceImpl.deductPointRange(deductPoint);
                        problemDescriptionMap.setProblemDes(indexProblemDes + ". " + pdObj.getProblemDescription() + ",扣" + deductPointRange + "分；");
                        problemDescriptionListFromPD.add(problemDescriptionMap);
                        indexProblemDes++;
                    }
                    gradeSixthMap.setProblemDescriptionList(problemDescriptionListFromPD);


                    gradeSixthMap.setPoint6(point6);
                    gradeSixthMap.setProblemDescriptionList(problemDescriptionListFromPD);

                    //获取第六级id
                    Integer sixthId = sixthObj.getSixthId();

                    //有问题第六级list
                    List<ProblemCollectDetail> sixthProblemList = parProblemCollectDetailMapper.getProblemDescriptionBySixthId(checkId, sixthId);
                    Double deductPoint6 = 0.0d;
                    String problemItem = "";
                    for (ProblemCollectDetail sixthProblemObj : sixthProblemList) {
                        //扣除分数环获取
                        deductPoint6 += Double.parseDouble(sixthProblemObj.getReducePoint());
                        //有问题项循环获取
                        problemItem += "有问题项：" + sixthProblemObj.getProblemDescription() + ",扣" + sixthProblemObj.getReducePoint() + "分；";
                    }
                    gradeSixthMap.setProblemItem(problemItem);
                    gradeSixthMap.setDeductPoint6(deductPoint6);
                    gradeSixthMap.setActuralPoint6(point6 - deductPoint6);

                    gradeSixthList.add(gradeSixthMap);
                    index++;
                }
                gradeFifthMap.setGradeSixthList(gradeSixthList);
                Double point5 = gradeSixthList.stream()
                        .mapToDouble(GradeSixthListMap::getPoint6)
                        .sum();
                //检查结果意见判断---保证项目小计分不足40分时，评定结果为不合格。
                if (pName5.equals("保证项目") && point5 < 40) {
                    flag = false;
                }
                gradeFifthMap.setPoint5(point5);
                Double deductPoint5 = gradeSixthList.stream()
                        .mapToDouble(GradeSixthListMap::getDeductPoint6)
                        .sum();
                //检查结果意见判断---保证项目中任意一项不得分时，评定结果为不合格。
                if (pName5.equals("保证项目") && deductPoint5 != 0.0d) {
                    flag = false;
                }
                gradeFifthMap.setDeductPoint5(deductPoint5);
                gradeFifthMap.setActuralPoint5(point5 - deductPoint5);
                gradeFifthList.add(gradeFifthMap);
            }
            evaluatieResultMap.setGradeFifthList(gradeFifthList);
            Double point = gradeFifthList.stream()
                    .mapToDouble(GradeFifthListMap::getPoint5)
                    .sum();
            //检查结果意见判断---检查项目总分不足70分，评定结果为不合格。
            if (point < 70) {
                flag = false;
            }
            evaluatieResultMap.setPoint(point);
            Double acturalPoint = gradeFifthList.stream()
                    .mapToDouble(GradeFifthListMap::getActuralPoint5)
                    .sum();
            evaluatieResultMap.setDeservePoint(point);
            evaluatieResultMap.setActuralPoint(acturalPoint);
            evaluatieResultMap.setFinalPoint(acturalPoint / point * 100);
            evaluatieResultMap.setDeductPoint(point - acturalPoint);
            if (flag) {
                evaluatieResultMap.setCheckSuggestion("合格");
            } else {
                evaluatieResultMap.setCheckSuggestion("不合格");
            }

            evaluatieResultList.add(evaluatieResultMap);
        }
        dataMap.setEvaluatieResultList(evaluatieResultList);

        //第一部分 --- 三、存在问题描述
        List<SecurityProblemListMap> securityProblemList = new ArrayList<>();
        List<EquipExistProblemDesVO> equipExistProblemDesList = parProblemCollectDetailMapper.getEquipExistProblemDesList(checkId, projectId);
        for (EquipExistProblemDesVO obj : equipExistProblemDesList) {
            SecurityProblemListMap securityProblemMap = new SecurityProblemListMap();
            Integer machineTypeNum = obj.getMachineType();
            String machineType = "无";
            if (reportServiceImpl.configIsNull(machineTypeNum)) {
                machineType = parSystemMapper.getName4ByName4Id(machineTypeNum);
            }
            securityProblemMap.setMachineType(machineType);
            securityProblemMap.setEquipNum(obj.getEquipNum());
            securityProblemMap.setNormsProvison(obj.getNormsProvison());
            String riskLevel=obj.getRiskPoint();
            switch(Integer.parseInt(obj.getRiskPoint())){
                case 4:
                    riskLevel="一级隐患";
                    break;
                case 3:
                    riskLevel="二级隐患";
                    break;
                case 2:
                    riskLevel="三级隐患";
                    break;
                case 1:
                    riskLevel="四级隐患";
                    break;
            }
            securityProblemMap.setRiskPoint(riskLevel);
            System.out.println(obj.getRemark() + "asdjjjj");
            if (!reportServiceImpl.configIsNull(obj.getRemark())) {
                securityProblemMap.setRemark(obj.getProblemDescription());
            } else {
                securityProblemMap.setRemark(obj.getRemark());
            }
            securityProblemList.add(securityProblemMap);
        }
        dataMap.setSecurityProblemList(securityProblemList);

        //第二部分
        List<CheckFourthListMap> checkFourthList = new ArrayList<>();
        List<CheckSuggestionVO> checkSuggestionList = parProblemCollectDetailMapper.getCheckSuggestionList(checkId, projectId);
        for (CheckSuggestionVO checkObj : checkSuggestionList) {
            CheckFourthListMap checkFourthMap = new CheckFourthListMap();
            checkFourthMap.setEquipNum(checkObj.getEquipNum());
            Integer machineTypeNum = checkObj.getMachineType();
            String machineType = "无";
            if (reportServiceImpl.configIsNull(machineTypeNum)) {
                machineType = parSystemMapper.getName4ByName4Id(machineTypeNum);
            }
            checkFourthMap.setMachineType(machineType);
            List<CheckSixthListMap> checkSixthList = new ArrayList<>();
            List<SixthProblemSuggestionListVO> sixthProblemSuggestionList = checkObj.getSixthProblemSuggestionList();
            for (SixthProblemSuggestionListVO sixthObj : sixthProblemSuggestionList) {
                CheckSixthListMap checkSixthMap = new CheckSixthListMap();
                checkSixthMap.setpName5(sixthObj.getpName5());
                checkSixthMap.setpName6(checkObj.getpName6());
                checkSixthMap.setCheckPart(sixthObj.getCheckPart());
                checkSixthMap.setNormsProvison(sixthObj.getNormsProvison());
                checkSixthMap.setProblemQua(sixthObj.getProblemQua());
                if (!reportServiceImpl.configIsNull(sixthObj.getRemark())) {
                    checkSixthMap.setRemark(sixthObj.getProblemDescription());
                } else {
                    checkSixthMap.setRemark(sixthObj.getRemark());
                }
                String problemListRiskPoint = "";
                switch (sixthObj.getRiskPoint()) {
                    case "提醒":
                        problemListRiskPoint = "提醒";
                        break;
                    case "1":
                        problemListRiskPoint = "四级隐患";
                        break;
                    case "2":
                        problemListRiskPoint = "三级隐患";
                        break;
                    case "3":
                        problemListRiskPoint = "二级隐患";
                        break;
                    case "4":
                        problemListRiskPoint = "一级隐患";
                        break;
                    default:
                        problemListRiskPoint = "";
                        break;
                }
                checkSixthMap.setRiskPoint(problemListRiskPoint);
                checkSixthMap.setSuggestion(sixthObj.getSuggestion());

                //处理图片
                checkSixthMap.setPicName(sixthObj.getPicName());
                checkSixthMap.setPicPath(sixthObj.getPicPath());
                List<String> picList = new ArrayList<>();
                JSONArray picNameArray = JSONArray.parseArray(checkSixthMap.getPicName());
                if (picNameArray == null || picNameArray.size() == 0) {
                    //报告本地测试
//                    String s = MDoc.getImageStr("E:\\tencent_File\\1296928795\\FileRecv\\123.png");
                    String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");
                    picList.add(s);
                } else {
                    for (int j = 0; j < picNameArray.size(); j++) {
                        //报告本地测试
//                        String s = MDoc.getImageStr("D:\\whutServer\\generatedCharts\\noPic.png");
                        String s = MDoc.getImageStr(checkSixthMap.getPicPath() + picNameArray.getString(j));
                        picList.add(s);
                    }
                }
                checkSixthMap.setPicList(picList);
                checkSixthList.add(checkSixthMap);
            }
            checkFourthMap.setCheckSixthList(checkSixthList);
            checkFourthList.add(checkFourthMap);
        }
        dataMap.setCheckFourthList(checkFourthList);

        //生成报告
        DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        String fileNameTime = dateTime.format(LocalDateTime.now());
        String reportName = dataMap.getProjectName() + "第三方评估报告" + fileNameTime;
        String ftlName = "thirdPartyEquipReport";


        BeanMap beanMap = new BeanMap(dataMap);

        return ReportCommonFunc.generateReport(beanMap, reportName, ftlName);
    }

}
